package furns.web;

import furns.entity.Manager;
import furns.service.ManagerService;
import furns.service.impl.ManagerServiceImpl;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@SuppressWarnings("all")
@WebServlet(name = "AdminServlet", urlPatterns = "/adminServlet")
public class AdminServlet extends BasicServlet {
    //创建一个ManagerServiceImpl对象,便于调用其方法
    private ManagerService managerService = new ManagerServiceImpl();
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从数据库中验证是否存在该管理员对象。若存在，则请求转发到 管理员页面，否则跳转到登录页面。

        //得到输入的管理员名称和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Manager manager = managerService.login(new Manager(null, username, password));
        if (manager != null) {  //说明数据库中存在该管理员信息，允许登录
            //将manager对象保存到session中
            request.getSession().setAttribute("manager", manager);
            //登录成功后，请求转发到指定页面
            request.getRequestDispatcher("/views/manage/manage_menu.jsp").forward(request, response);
        } else {
            //将提示信息保存到request域中。因为是请求转发，因此是同一个request对象
            request.setAttribute("msg", "用户名或密码错误");
            //密码错误，将用户输入的用户名保存到request域中并显示在登录页面中
            request.setAttribute("username", username);
            //登录失败，跳转到登录页面
            request.getRequestDispatcher("/views/manage/manage_login.jsp").forward(request, response);
        }
    }

}